package com.example.user.coolrun.runnershign;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.user.coolrun.R;
import com.example.user.coolrun.highscore.HighscoreAdapter;

public class HighScoreForm extends Activity {

    private HighscoreAdapter highScoreAdapter = null;
    private EditText nameField;
    private TextView scoreField;
    private Integer score;
    // ---------------------------------------------------
    @Override
    public void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_high_score_form);

        highScoreAdapter = new HighscoreAdapter(this);
        highScoreAdapter.open();

        // Find form elements
        nameField = (EditText) findViewById(R.id.title);
        nameField.setSingleLine(true);
        nameField.setOnKeyListener(new View.OnKeyListener() {

            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    // hide keyboard when ENTER is pressed
                    InputMethodManager imm = (InputMethodManager)getApplicationContext().getSystemService(
                            Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
                return false;
            }
        });

        scoreField = (TextView) findViewById(R.id.score);
        android.widget.Button confirmButton = (Button) findViewById(R.id.confirm);

        // Performe save
        confirmButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                saveState();
            }
        });

        // Get Score
        score = (savedInstanceState == null) ? null : (Integer) savedInstanceState.getSerializable("score");
        if (score == null) {
            Bundle extras = getIntent().getExtras();
            score = extras != null ? extras.getInt("score") : null;
        }
        scoreField.setText(score.toString());

        // Get Last Saved Name
        Cursor cursor = highScoreAdapter.fetchLastEntry();
        startManagingCursor(cursor);
        if(cursor.getCount() > 0) {
            nameField.setText(cursor.getString(cursor.getColumnIndexOrThrow(HighscoreAdapter.KEY_NAME)));
        }
        cursor.close();
    }

    // ---------------------------------------------------
    // Save Entry
    private void saveState() {
        String name 	=  nameField.getText().toString();
        String score 	=  scoreField.getText().toString();

        int isonline = 0;

        if(name.length() > 0) {

            // Save HS locally
            try {
                highScoreAdapter.createHighscore(score, name, isonline);
            } catch (Exception e) {
                Log.w(Settings.LOG_TAG, "create highscore threw an exception");
                Log.w(Settings.LOG_TAG, "Maybe a double attempt? HTC Sensation does that for example");
                return;
            }

            highScoreAdapter.close();

            setResult(RESULT_OK);
            finish();
        } else {
            highScoreAdapter.toastMessage("请输入姓名");
        }
    }

    // ---------------------------------------------------------
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        saveState();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (highScoreAdapter != null) {
            highScoreAdapter.close();
        }
    }
}

